package com.dzwww.recommend.rule.service.aspect;

import cn.hutool.core.util.StrUtil;
import com.dzwww.recommend.rule.common.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * Service日志切面
 * <p>
 * <p>
 *   @author lixin
 *   @date 2018/3/31 下午1:29
 *   @version 1.0
 */
@Component
@Aspect
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
@Slf4j
public class ServiceLogAspect {

    /**
     * 非业务异常记录
     *
     * @param pjd pjd
     * @return Object
     * @throws Throwable Throwable
     */
    @Around("execution(* com.dzwww.recommend.rule.service..*(..))")
    public Object serviceLog(ProceedingJoinPoint pjd) throws Throwable {
        Object result;

        Signature signature = pjd.getSignature();
        String className = signature.getDeclaringTypeName();
        String methodName = signature.getName();
        List<Object> argList = Arrays.asList(pjd.getArgs());

        try {
            result = pjd.proceed();
        } catch (Throwable e) {
            String errorMsg = StrUtil.format("【Service】【class】= {}, 【method】= {}, 出现异常, 【param】= {}", className, methodName, argList, e);
            if (e instanceof ApiException) {
                log.warn(errorMsg);
            } else {
                log.error(errorMsg);
            }
            throw e;
        }

        return result;
    }

}
